<?php

namespace app\api\controller;

use app\admin\model\Harm AS HarmMdl;
use app\admin\model\Userfarm;
use app\admin\model\Medicament;

class Harm extends BaseController
{

    /**
     * 获取病害/虫害
     */
    public function getHarms()
    {
        $param = self::getHttpParam();

        if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 不能为空');
        }
        if (!in_array($param->type, [1, 2])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 格式不正确');
        }

        $where = [
            'type' => $param->type
        ];

        if (!empty($param->farmId)) {
            $farmInfo = Userfarm::where(['id' => $param->farmId])->field('cropId')->find();
            $cropId = $farmInfo['cropId'];
            $where['crops'] = ['like', '%' . $cropId . '%'];
        }

        $model = new HarmMdl();
        $fields = 'id, name, imgUrl';
        $order = 'createDate DESC';
        $result = $model->where($where)->field($fields)->order($order)->select();
        if (!$result) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关数据');
        }

        /*foreach ($result as $item) {
            $medicamentList = Medicament::whereIn('id', $item['medicaments'])->field('id, name')->select();

            $item['medicamentList'] = $medicamentList;
            unset($item['medicaments']);
        }*/

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result);
    }

    /**
     * 选择病害/虫害
     */
    public function selectedHarm()
    {
        $param = self::getHttpParam();

        if (empty($param->harmId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'harmId 不能为空');
        }

        $where = [
            'id' => $param->harmId
        ];
        $model = new HarmMdl();
        $field = 'medicaments';
        $item = $model->where($where)->field($field)->find();
        if (!$item) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到相关数据');
        }

        $medicamentList = Medicament::whereIn('id', $item['medicaments'])->field('id, name, isAddwater')->select();

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $medicamentList);
    }

}